const express = require('express');
const axios = require('axios');
const router = express.Router();

// OneNET IoT API configuration
const API_BASE_URL = 'https://iot-api.heclouds.com';
const AUTH_HEADER = 'version=2018-10-31&res=userid%2F182782&et=1847292568&method=md5&sign=CjAgX6WFXHZGNnoD1I42bg%3D%3D';

// Device configuration
const DEFAULT_PRODUCT_ID = '9InW4cu14V';
const DEFAULT_DEVICE_NAME = 'a001';

/**
 * @route GET /api/iot/device-property
 * @description 查询设备的最新属性数据
 * 
 * 接口说明：
 * 1. 使用预设的产品ID和设备名称
 * 2. 调用 OneNET 平台的物模型接口
 * 3. 返回设备的所有属性数据
 */
router.get('/device-property', async (req, res) => {
  try {
    // Use default values instead of query parameters
    const product_id = DEFAULT_PRODUCT_ID;
    const device_name = DEFAULT_DEVICE_NAME;

    console.log('\n=== IoT 设备属性请求 ===');
    console.log(`时间: ${new Date().toISOString()}`);
    console.log(`产品ID: ${product_id}`);
    console.log(`设备名称: ${device_name}`);

    // Call OneNET API
    const response = await axios.get(`${API_BASE_URL}/thingmodel/query-device-property`, {
      params: {
        product_id,
        device_name
      },
      headers: {
        'authorization': 'version=2018-10-31&res=userid%2F182782&et=1847292568&method=md5&sign=CjAgX6WFXHZGNnoD1I42bg%3D%3D'
      }
    });

    console.log('\n=== 完整的 JSON 响应数据 ===');
    console.log(JSON.stringify(response.data, null, 2));
    console.log('\n=== 响应结束 ===\n');

    // Return the API response
    res.json(response.data);
  } catch (error) {
    console.error('\n=== IoT 设备属性请求错误 ===');
    console.error('时间:', new Date().toISOString());
    console.error('错误信息:', error.message);
    if (error.response) {
      console.error('响应状态:', error.response.status);
      console.error('错误详情:', JSON.stringify(error.response.data, null, 2));
    }
    console.error('=== 错误日志结束 ===\n');

    res.status(error.response?.status || 500).json({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || '服务器内部错误',
      request_id: new Date().getTime().toString()
    });
  }
});

module.exports = router; 